package com.qd.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.pay.domain.OrderRespDTO;
import com.qd.pay.model.OrderResp;
import com.qd.pay.repository.OrderRespRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderRespService {

    private final OrderRespRepository orderRespRepository;
    @Resource
    private RedisTemplateUtil<OrderResp> redisTemplateUtil;

    private static final String PREFIX_ID = "m_order_resp_respId_{0}";

    @Transactional(rollbackFor = Exception.class)
    public OrderResp save(OrderResp model) throws ApiException {
        try {
            if (!orderRespRepository.save(model)) {
                throw new ApiException(ApiResult.error());
            }
            return model;
        } finally {
            clearCache(model);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(OrderResp model) throws ApiException {
        final OrderResp historyModel = Optional.ofNullable(getById(model.getRespId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        try {
            if (!orderRespRepository.updateById(model)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean removeById(String respId) throws ApiException {
        final OrderResp historyModel = Optional.ofNullable(getById(respId)).orElseThrow(() -> new ApiException("ID不存在,不能删除"));
        try {
            if (!orderRespRepository.removeById(respId)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    public Boolean isExists(String respId) {
        return orderRespRepository.isExists(respId);
    }

    public OrderResp getById(String respId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, respId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY * 3), () -> orderRespRepository.getById(respId), OrderResp.class);
    }

    public OrderResp getOne(String orderId) {
        return orderRespRepository.getOne(new QueryWrapper<OrderResp>().eq("order_id", orderId), false);
    }

    public IPage<OrderRespDTO> page(Page<OrderRespDTO> page, OrderResp model) {
        QueryWrapper<OrderResp> queryWrapper = new QueryWrapper<>(model);
        IPage<OrderResp> iPage = orderRespRepository.page(page.convert(this::dtoToModel), queryWrapper);
        return iPage.convert(this::modelToDto);
    }


    private void clearCache(OrderResp model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getRespId());
        redisTemplateUtil.deleteByKey(key);
    }

    public OrderRespDTO modelToDto(OrderResp model) {
        if (null == model) {
            return null;
        }
        OrderRespDTO dto = new OrderRespDTO();
        dto.setRespId(model.getRespId());
        dto.setPayCode(model.getPayCode());
        dto.setTimeStart(model.getTimeStart());
        dto.setOrderId(model.getOrderId());
        dto.setErrMsg(model.getErrMsg());
        model.freeData();
        return dto;
    }

    public OrderResp dtoToModel(OrderRespDTO dto) {
        if (null == dto) {
            return null;
        }
        OrderResp model = new OrderResp();
        model.setRespId(dto.getRespId());
        model.setPayCode(dto.getPayCode());
        model.setTimeStart(dto.getTimeStart());
        model.setOrderId(dto.getOrderId());
        model.setErrMsg(dto.getErrMsg());
        dto.freeData();
        return model;
    }

}